package com.zj.config;

import org.springframework.context.annotation.DeferredImportSelector;
import org.springframework.core.type.AnnotationMetadata;

import java.util.ArrayList;
import java.util.List;

/*
DeferredImportSelector继承自ImportSelector，其核心作用是将配置类导入逻辑延迟到所有配置类解析完成后执行。
这允许它访问完整的配置信息（如已注册的Bean、环境变量等），从而根据条件动态选择需要导入的配置类，
特别是在涉及条件装配（如@Conditional注解）时尤为有用
 */
public class CustomDeferredImportSelector implements DeferredImportSelector {
    @Override
    public String[] selectImports(AnnotationMetadata importingClassMetadata) {
        return new String[]{"com.zj.service.impl.UserServiceImpl2"};
    }
/*
如果沒有没有重写getImportGroup方法，则直接走selectImports方法
如果由重写getImportGroup方法，如果返回DeferredImportSelector.Group实现类，则执行其process方法
如果没有实现DeferredImportSelector.Group，返回null，则执行DefaultDeferredImportSelectorGroup中的process方法
最后执行group的selectImports()方法。DeferredImportSelector实现类的selectImports不一定执行。
org.springframework.context.annotation.ConfigurationClassParser.DeferredImportSelectorGrouping
 		public Iterable<Group.Entry> getImports() {
			for (DeferredImportSelectorHolder deferredImport : this.deferredImports) {
				this.group.process(deferredImport.getConfigurationClass().getMetadata(),
						deferredImport.getImportSelector());
			}
			return this.group.selectImports();
		}

 */
    @Override
    public Class<? extends Group> getImportGroup() {
        return MyGroup.class;
//        return null;
    }

    private static class MyGroup implements DeferredImportSelector.Group{

        private final List<Entry> imports = new ArrayList<>();

        @Override
        public void process(AnnotationMetadata metadata, DeferredImportSelector selector) {
            //这里调用了DeferredImportSelector的selectImports方法
            for (String importClassName : selector.selectImports(metadata)) {
                this.imports.add(new Entry(metadata, importClassName));
            }
        }

        @Override
        public Iterable<Entry> selectImports() {
            return this.imports;
        }
    }
}
